/*
 * @Author: fengshan0525 2735332396@qq.com
 * @Date: 2023-03-17 20:42:43
 * @LastEditors: asanupup 15465106+asanupup@user.noreply.gitee.com
 * @LastEditTime: 2025-07-25 10:57:27
 * @FilePath: \nest-template\src\app.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { UserFields } from 'types/modelFields';
import { JwtService } from '@nestjs/jwt';
import { AdminUsers } from '@libs/db/models/user.model';
import { AmdinRole } from '@libs/db/models/role.model';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { initialRoleInfo, initialUserInfo, initialMenu } from 'utils/init';
import { AdminMenu } from '@libs/db/models/menu.model';

@Injectable()
export class AppService {
  constructor(
    private readonly ConfigService: ConfigService,
    private readonly JwtService: JwtService,
    @InjectModel('AdminUsers') private readonly userModel: Model<AdminUsers>,
    @InjectModel('AmdinRole') private readonly roleModel: Model<AmdinRole>,
    @InjectModel('AdminMenu') private readonly menuModel: Model<AdminMenu>,
  ) { }
  /**
   * @breif: 初始化系统，创建角色、路由、账号
   * @return {*}
   */
  async initSystem() {
    try {
      const userDoc = await this.userModel.create(initialUserInfo);
      await userDoc.save();
      const roleDoc = await this.roleModel.create(initialRoleInfo);
      await roleDoc.save();

      initialMenu.forEach(async (item) => {
        const menuDoc = await this.menuModel.create(item);
        await menuDoc.save();
      });
      const firstUser = await this.userModel.findOne({telephone: initialUserInfo.telephone})
      return this.genToken(initialUserInfo.roles[0], firstUser._id);
    } catch (e) {
      return new HttpException('初始化失败', HttpStatus.FORBIDDEN);
    }
  }
  async login(body: UserFields) {
    console.log(body,'body');

    const doc = await this.userModel
      .findOne({ username: body.username })
      .exec();
    // 如果数据库中没有admin用户且登录账号为admin，说明系统还没有初始化，此时应初始化系统
    if (body.username === 'Admin' && !doc) {
      return this.initSystem();
    }
    if (doc) {
      if (doc.password !== body.password) {
        return new HttpException('用户名/密码错误', HttpStatus.FORBIDDEN);
      } else {
        return this.genToken(doc.roles, doc._id);
      }
    } else {
      return new HttpException('用户名/密码错误', HttpStatus.FORBIDDEN);
    }
  }
  genToken(roles: string[], _id: string): Object {
    const Authorization = this.JwtService.sign(
      { roles, _id },
      { secret: this.ConfigService.get<string>('SECRET_KEY') },
    );
    const resData = {
      Authorization,
    };
    return resData;
  }
}
